package com.dianrui.firemenmonitor.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import android.widget.ScrollView;


import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;


import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.dianrui.firemenmonitor.Constant;
import com.dianrui.firemenmonitor.R;
import com.dianrui.firemenmonitor.adapter.MainArticleAdapter;
import com.dianrui.firemenmonitor.bean.MainArticleTop;
import com.dianrui.firemenmonitor.util.LocationUtils;
import com.dianrui.firemenmonitor.util.MapFixUtil;
import com.dianrui.firemenmonitor.util.MyUtil;
import com.dianrui.firemenmonitor.util.OkHttpUtils;
import com.dianrui.firemenmonitor.util.StringUtils;
import com.dianrui.firemenmonitor.util.ToastUtil;
import com.dianrui.firemenmonitor.util.Url;
import com.dianrui.firemenmonitor.view.InnerListview;
import com.dianrui.firemenmonitor.view.PulltoRefresh.PullToRefreshBase;
import com.dianrui.firemenmonitor.view.PulltoRefresh.PullToRefreshScrollView;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {
    public LocationClient mLocationClient = null;
    private List<MainArticleTop> mainArticleTopList = new ArrayList<>();
    private MainArticleAdapter mainArticleAdapter;
    private long mclicktime;
    private Timer timer;
    private TimerTask task;
    private double latitude;
    private double longitude;
    private double updatelatitude;
    private double updatelongitude;
    private double distance;
    private boolean isFirstLoc = true;


    @BindView(R.id.scrollView)
    PullToRefreshScrollView scrollView;
    @BindView(R.id.articles_list)
    InnerListview articlesList;

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        customInit(R.color.blue_518bfa);
        mainArticleAdapter = new MainArticleAdapter(MainActivity.this, mainArticleTopList);
        articlesList.setAdapter(mainArticleAdapter);
        setTarget();
        getArticle();
        mainArticleAdapter.setOnButtonClickListener(new MainArticleAdapter.MainArticleClickListener() {
            @Override
            public void onMainArticleClick(String htmlurl, String titles) {
                Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("url", htmlurl);
                bundle.putString("titles", titles);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        scrollView.setMode(PullToRefreshBase.Mode.BOTH);
        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getArticle();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getArticle();
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            startLocation();
        }

        StartSendLat();

    }

    //开始定位
    private void startLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new bdAbstractLocationListener());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setPriority(LocationClientOption.GpsFirst);
        option.setCoorType("bd09ll");
        option.setScanSpan(3000);
        option.setOpenGps(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setWifiCacheTimeOut(6 * 60 * 1000);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationPoiList(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    private void StartSendLat() {
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                sendLatAndLng(longitude,latitude);

            }
        };
        timer.schedule(task, 0, 10000);
    }




    private void sendLatAndLng(double updatelongitude,double updatelatitude) {
        JsonObject jsonObject = new JsonObject();
        if (latitude == 0.0 && longitude == 0.0) {

        }else {
            jsonObject.addProperty("latitude", updatelongitude + "," + updatelatitude);
        }
        OkHttpUtils.getInstance().postWithMemberToken(Url.OUTPOLICE, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {

                            } else {

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public class bdAbstractLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            latitude = bdLocation.getLatitude();    //获取纬度信息
            longitude = bdLocation.getLongitude();    //获取经度信息
            if (isFirstLoc) {
                isFirstLoc = false;
            }
        }
    }

    /**
     * 首次运行弹出协议和隐私对话框判断
     **/
    private void setTarget() {
        SharedPreferences share = getSharedPreferences("FirstInfo", MODE_PRIVATE);
        SharedPreferences.Editor editor = share.edit();
        editor.putBoolean("isFirstIn", false);
        editor.apply();
    }

    private void getArticle() {
        OkHttpUtils.getInstance().postRequests(Url.CLASSIFCATION, "", new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (mainArticleTopList != null) {
                                    mainArticleTopList.clear();
                                }
                                if (scrollView != null) {
                                    scrollView.onRefreshComplete();
                                }
                                JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("lists");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        MainArticleTop mainArticleTop = new MainArticleTop();
                                        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                                        mainArticleTop.id = jsonObject1.optString("id");
                                        mainArticleTop.thumbnail = jsonObject1.optString("thumbnail");
                                        mainArticleTop.post_title = jsonObject1.optString("post_title");
                                        mainArticleTop.html_href = jsonObject1.optString("html_href");
                                        mainArticleTop.create_time = jsonObject1.optLong("create_time");
                                        mainArticleTopList.add(mainArticleTop);
                                    }
                                    if (mainArticleAdapter != null) {
                                        mainArticleAdapter.refresh(mainArticleTopList);
                                    }

                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    @OnClick({R.id.person_img, R.id.more, R.id.attendance_layout, R.id.track_layout, R.id.study_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.person_img:
                JumpActivitys(PersonCenterActivity.class);
                break;
            case R.id.attendance_layout:
                if (!MyUtil.isGpsEnable(MainActivity.this)) {
                    showOpenGpsDialog();
                } else {
                    JumpActivitys(AttendaceActivity.class);
                }
                break;
            case R.id.track_layout:
                JumpActivitys(TrackDetailsActivity.class);
                break;
            case R.id.study_layout:
                JumpActivitys(StudyActivity.class);
                break;

            case R.id.more:
                JumpActivitys(StudyActivity.class);
                break;

            default:
                break;
        }
    }

    private void showOpenGpsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.RcDialog);
        final View view2 = LayoutInflater.from(MainActivity.this).inflate(R.layout.open_gps_dialog, null);
        final AlertDialog pausedialog = builder.create();
        pausedialog.setView(view2);
        pausedialog.setCanceledOnTouchOutside(false);
        pausedialog.show();
        final Button yes = view2.findViewById(R.id.yes);

        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pausedialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
    }





    public void CancelTask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mclicktime < Constant.CLICKTIME) {
                this.finish();
                MyUtil.getInstance().clear();
                Process.killProcess(Process.myPid());
                System.exit(0);
                if (mLocationClient != null) {
                    mLocationClient.stop();
                }
                CancelTask();
                LocationUtils.getInstance(MainActivity.this).removeLocationUpdatesListener();
            } else {
                ToastUtil.showToast(getString(R.string.press_exit));
                mclicktime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationUtils.getInstance(MainActivity.this).removeLocationUpdatesListener();
    }
}
